{% extends 'dashboard/base.html' %}
{% load static %}

{% block title %}仪表盘 - 后台管理{% endblock %}

{% block content %}
<div class="page-header">
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center">
        <div>
            <h1 class="h2 mb-1"><i class="bi bi-speedometer2 me-2 text-primary"></i>后台管理-仪表盘</h1>
            <p class="text-muted mb-0">系统概览和关键指标</p>
        </div>
        <div class="btn-toolbar mb-2 mb-md-0">
            <button class="btn btn-outline-primary" onclick="updateStats()">
                <i class="bi bi-arrow-clockwise"></i> 刷新数据
            </button>
        </div>
    </div>
</div>

<!-- 统计卡片 -->
<div class="row mb-4">
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stats-card border-start-primary h-100">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                            总用户数</div>
                        <div class="h3 mb-0 font-weight-bold text-gray-800">{{ total_users }}</div>
                        <div class="mt-2 text-success small">
                            <i class="bi bi-arrow-up"></i> 本周新增 {{ new_users_week }} 人
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="bi bi-people fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stats-card border-start-success h-100">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                            总活动数</div>
                        <div class="h3 mb-0 font-weight-bold text-gray-800">{{ total_activities }}</div>
                        <div class="mt-2 text-info small">
                            <i class="bi bi-clock"></i> {{ pending_activities }} 待审核
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="bi bi-calendar-event fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stats-card border-start-warning h-100">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                            今日活跃</div>
                        <div class="h3 mb-0 font-weight-bold text-gray-800">{{ today_users }}</div>
                        <div class="mt-2 text-muted small">
                            注册用户 / 访问量
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="bi bi-activity fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stats-card border-start-info h-100">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                            参与率</div>
                        <div class="h3 mb-0 font-weight-bold text-gray-800">{{ participation_rate }}%</div>
                        <div class="mt-2 text-muted small">
                            活动平均参与率
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="bi bi-person-check fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- 图表区域 -->
    <div class="col-lg-8">
        <div class="card shadow mb-4">
            <div class="card-header bg-white py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="bi bi-graph-up me-2"></i>平台增长趋势 (最近30天)
                </h6>
                <div class="btn-group btn-group-sm">
                    <button class="btn btn-outline-primary active" data-period="week">周</button>
                    <button class="btn btn-outline-primary" data-period="month">月</button>
                    <button class="btn btn-outline-primary" data-period="quarter">季</button>
                </div>
            </div>
            <div class="card-body">
                <div class="chart-area" style="height: 320px;">
                    <canvas id="userGrowthChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- 右侧信息 -->
    <div class="col-lg-4">
        <!-- 待审核活动 -->
        <div class="card shadow mb-4">
            <div class="card-header bg-white py-3">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="bi bi-clock-history me-2"></i>待审核活动
                </h6>
            </div>
            <div class="card-body p-0">
                {% for activity in recent_pending_activities %}
                <div class="border-bottom p-3 hover-light">
                    <div class="d-flex align-items-center">
                        <div class="flex-grow-1">
                            <h6 class="mb-1 text-dark">{{ activity.title|truncatechars:25 }}</h6>
                            <small class="text-muted">
                                <i class="bi bi-person me-1"></i>{{ activity.creator.username }}
                            </small>
                        </div>
                        <a href="{% url 'dashboard:activity_management' %}?status=pending"
                           class="btn btn-sm btn-outline-primary">审核</a>
                    </div>
                </div>
                {% empty %}
                <div class="text-center py-4">
                    <i class="bi bi-check-circle display-4 text-success"></i>
                    <p class="text-muted mt-2 mb-0">暂无待审核活动</p>
                </div>
                {% endfor %}
            </div>
        </div>

        <!-- 最新用户 -->
        <div class="card shadow">
            <div class="card-header bg-white py-3">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="bi bi-person-plus me-2"></i>最新注册用户
                </h6>
            </div>
            <div class="card-body p-0">
                {% for user in recent_users %}
                <div class="border-bottom p-3 hover-light">
                    <div class="d-flex align-items-center">
                        <div class="avatar-sm bg-primary rounded-circle d-flex align-items-center justify-content-center me-3">
                            <i class="bi bi-person text-white"></i>
                        </div>
                        <div class="flex-grow-1">
                            <span class="fw-bold text-dark">{{ user.username }}</span>
                            <br>
                            <small class="text-muted">{{ user.date_joined|date:"m-d H:i" }}</small>
                        </div>
                    </div>
                </div>
                {% endfor %}
            </div>
        </div>
    </div>
</div>

<!-- 操作日志 -->
<div class="row mt-4">
    <div class="col-12">
        <div class="card shadow">
            <div class="card-header bg-white py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="bi bi-clock-history me-2"></i>最近操作日志
                </h6>
                <a href="{% url 'dashboard:admin_logs' %}" class="btn btn-sm btn-outline-primary">
                    查看全部 <i class="bi bi-arrow-right"></i>
                </a>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-sm table-hover">
                        <thead class="bg-light">
                            <tr>
                                <th>管理员</th>
                                <th>操作类型</th>
                                <th>描述</th>
                                <th>IP地址</th>
                                <th>时间</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for log in recent_logs %}
                            <tr class="clickable-row" data-href="{% url 'dashboard:admin_logs' %}?search={{ log.admin.username }}">
                                <td>
                                    <div class="d-flex align-items-center">
                                        <div class="avatar-xs bg-primary rounded-circle d-flex align-items-center justify-content-center me-2">
                                            <i class="bi bi-person text-white" style="font-size: 0.7rem;"></i>
                                        </div>
                                        <strong>{{ log.admin.username }}</strong>
                                    </div>
                                </td>
                                <td>
                                    <span class="badge
                                        {% if log.action == 'user_manage' %}bg-primary
                                        {% elif log.action == 'activity_manage' %}bg-success
                                        {% else %}bg-info{% endif %}">
                                        <i class="bi bi-{% if log.action == 'user_manage' %}people{% elif log.action == 'activity_manage' %}calendar-event{% else %}gear{% endif %} me-1"></i>
                                        {{ log.get_action_display }}
                                    </span>
                                </td>
                                <td title="{{ log.description }}">
                                    {{ log.description|truncatechars:40 }}
                                </td>
                                <td><code class="text-muted">{{ log.ip_address }}</code></td>
                                <td class="text-muted">{{ log.created_at|date:"m-d H:i" }}</td>
                            </tr>
                            {% empty %}
                            <tr>
                                <td colspan="5" class="text-center text-muted py-4">
                                    <i class="bi bi-journal-x display-4 d-block mb-2"></i>
                                    暂无操作日志
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    // 添加悬停效果
    document.addEventListener('DOMContentLoaded', function() {
        // 为可点击行添加悬停效果
        document.querySelectorAll('.clickable-row').forEach(row => {
            row.style.cursor = 'pointer';
            row.addEventListener('click', function() {
                window.location.href = this.dataset.href;
            });
        });

        // 为卡片添加悬停类
        document.querySelectorAll('.hover-light').forEach(item => {
            item.addEventListener('mouseenter', function() {
                this.style.backgroundColor = '#f8f9fa';
            });
            item.addEventListener('mouseleave', function() {
                this.style.backgroundColor = '';
            });
        });
    });

    // 用户增长图表
    const userGrowthData = {{ user_growth_data|safe }};
    const activityGrowthData = {{ activity_growth_data|safe }};

    const dates = userGrowthData.map(item => item.date);
    const userCounts = userGrowthData.map(item => item.count);
    const activityCounts = activityGrowthData.map(item => item.count);

    const ctx = document.getElementById('userGrowthChart').getContext('2d');
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: dates,
            datasets: [
                {
                    label: '新增用户',
                    data: userCounts,
                    borderColor: 'rgb(67, 97, 238)',
                    backgroundColor: 'rgba(67, 97, 238, 0.1)',
                    tension: 0.4,
                    fill: true,
                    borderWidth: 2
                },
                {
                    label: '新增活动',
                    data: activityCounts,
                    borderColor: 'rgb(40, 167, 69)',
                    backgroundColor: 'rgba(40, 167, 69, 0.1)',
                    tension: 0.4,
                    fill: true,
                    borderWidth: 2
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                },
                tooltip: {
                    mode: 'index',
                    intersect: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: {
                        drawBorder: false
                    }
                },
                x: {
                    grid: {
                        display: false
                    }
                }
            }
        }
    });

    // 实时更新统计数据
    function updateStats() {
        const btn = event.target;
        const originalText = btn.innerHTML;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> 刷新中...';
        btn.disabled = true;

        fetch('{% url "dashboard:get_dashboard_stats" %}')
            .then(response => response.json())
            .then(data => {
                location.reload();
            })
            .catch(error => {
                console.error('Error:', error);
                btn.innerHTML = originalText;
                btn.disabled = false;
            });
    }

    // 每60秒更新一次
    setInterval(updateStats, 60000);
</script>

<style>
    .border-start-primary { border-left-color: #4361ee !important; }
    .border-start-success { border-left-color: #28a745 !important; }
    .border-start-warning { border-left-color: #ffc107 !important; }
    .border-start-info { border-left-color: #17a2b8 !important; }

    .avatar-sm {
        width: 32px;
        height: 32px;
    }

    .avatar-xs {
        width: 24px;
        height: 24px;
    }

    .hover-light:hover {
        background-color: #f8f9fa;
        transition: background-color 0.2s;
    }
</style>
{% endblock %}